package com.laowang.common.utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SFTPv3Client;
import ch.ethz.ssh2.Session;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

/**
 * @Auther laowang
 * @Date 2023/4/19
 * @Description
 */

@Slf4j
public class FilesPull {

    public static String img_path ="/www/wwwroot/47.115.226.133/images/";

    public static String filePull(MultipartFile file) throws IOException {

        String user = "root";
        String pass = "Cheyouhui963851";
        String host = "47.115.226.133";

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".")+1);  // 获得文件原始名
        String currentName = WXPayUtil.generateNonceStr()+"."+suffix;
        //String  nweName = writeFile(file.getInputStream(),currentName);
        //String[] split = StringUtils.split(nweName, "/");
        Connection con = new Connection(host);
        try
        {
            // 链接linux服务器 如果成功,返回true
            con.connect();
            boolean isAuthed = con.authenticateWithPassword(user, pass);
            System.out.println("isAuthed====" + isAuthed);

            SCPClient scpClient = con.createSCPClient();   // 创建客户端
            // scpClient.put("localFiles", "remoteDirectory"); //从本地复制文件到远程目录
            // scpClient.get("remoteFiles","localDirectory"); //从远程获取文件
            String directory = DateUtils.getFormatDate(DateUtils.getCurrentTime(), "yyyyMMddHH");
            SFTPv3Client sftpv3Client = new SFTPv3Client(con);
            String path = img_path + directory + "/";
            try {

                File directoryFile = new File(path);
                if (!directoryFile.exists()) {
                    sftpv3Client.mkdir(path, 755); //远程新建目录
                }

            } catch (Exception e) {
                log.error(e.getMessage());
            }
            scpClient.put(file.getBytes(), currentName,"/www/wwwroot/47.115.226.133/images/"+directory+"/","0777"); // 从本地复制文件到远程目录


//             SFTPv3Client sftpClient = new SFTPv3Client(con);
//            sftpClient.mv();
//            sftpClient.close();

            // sftpClient.mkdir("newRemoteDir", 6); //远程新建目录
            // sftpClient.rmdir(""); //远程删除目录
            //
            // sftpClient.createFile("newRemoteFile"); //远程新建文件
            // sftpClient.openFileRW("remoteFile"); //远程打开文件,可进行读写

            Session session = con.openSession();
            session.execCommand("uname -a && date && uptime && who");
            // 远程执行命令

            // 显示执行命令后的信息
            System.out.println("Here is some information about the remote host:");
            //InputStream stdout = new StreamGobbler(session.getStdout());

            //BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

            /*while (true) {
                String line = br.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }*/

            /* Show exit status, if available (otherwise "null") */

            System.out.println("ExitCode: " + session.getExitStatus());

            session.close();
            con.close();
            //return "https://www.jvvftpv.cn/web/"+nweName;
            System.out.println("http://47.115.226.133/images/"+ directory +"/"+currentName);
            return "http://47.115.226.133/images/"+ directory +"/"+currentName;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return "";
    }


    public static String writeFile(InputStream inputStream, String fileName) {
        FileOutputStream fileOutputStream = null;
        try {
            String directory = DateUtils.getFormatDate(DateUtils.getCurrentTime(), "yyyyMMdd");
            File file = getFile(directory, fileName);
            fileOutputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int n = 0;
            while ((n = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, n);
            }
            fileOutputStream.close();
            return directory + "/" + fileName;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return "";
    }


    public static File getFile(String directory, String fileName) {
        try {
            String path = img_path + directory + "/";
            File directoryFile = new File(path);
            if (!directoryFile.exists()) {
                directoryFile.mkdirs();
            }
            path = path + fileName;
            File file = new File(path);
            return file;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
            , MediaType.MULTIPART_FORM_DATA_VALUE
            , true
            , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }


    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Administrator\\Desktop\\新建文件夹\\64.jpg");

        FilesPull.filePull(getMultipartFile(file));
    }
}
